// Main process entry point
const { app, BrowserWindow } = require('electron');
const path = require('path');
const Database = require('../database/db');
const VocabularyService = require('../services/vocabulary/vocabularyService');
const CourseService = require('../services/course/courseService');

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
try {
  if (require('electron-squirrel-startup')) {
    app.quit();
  }
} catch (e) {
  // electron-squirrel-startup not installed
  console.log('electron-squirrel-startup not found');
}

// Database and service initialization
let db = null;
let vocabularyService = null;
let courseService = null;

const initializeServices = async () => {
  // Initialize database
  db = new Database();
  // Use the database file with data instead of creating a new empty one
  const dataPath = path.join(__dirname, '../data/ielts_vocabulary.db');
  db.init(dataPath);

  // Initialize services
  vocabularyService = new VocabularyService(db);
  await vocabularyService.init();

  courseService = new CourseService(db);
  await courseService.init();

};

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  // 禁用缓存以支持热更新
  mainWindow.webContents.session.clearCache();
  mainWindow.webContents.session.clearStorageData();

  // 设置Content Security Policy
  mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [
          "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self' https://openapi.youdao.com; img-src 'self' data:; font-src 'self' data:; media-src 'self' https://openapi.youdao.com;",
        ],
      },
    });
  });

  // and load the index.html of the app.
  if (process.env.NODE_ENV === 'development') {
    const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL || 'http://localhost:5173';
    mainWindow.loadURL(VITE_DEV_SERVER_URL);

    // 在开发模式下打开开发者工具
    mainWindow.webContents.openDevTools();
  } else {
    // 生产模式加载本地文件
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
  }

  // 禁用页面缓存
  mainWindow.webContents.on('dom-ready', () => {
    mainWindow.webContents.executeJavaScript(`
      // 禁用页面缓存
      window.addEventListener('beforeunload', function() {
        // 页面卸载时的操作
      });
    `);
  });

  return mainWindow;
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  try {
    await initializeServices();
    createWindow();
  } catch (error) {
    console.error('Failed to initialize services:', error);
  }
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('before-quit', () => {
  // Close database connection before quitting
  if (db) {
    db.close();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
